package com.sca.schedule.service.impl;

import com.sca.schedule.config.RabbitConfig;
import com.sca.schedule.entity.SimpleTimerJob;
import com.sca.schedule.service.TimerService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author liuxianfei
 * @since 2020/11/20 13:36
 */
@Slf4j
@Service
public class TimerServiceImpl implements TimerService {

    private final Scheduler scheduler;
    private final RabbitTemplate rabbitTemplate;

    public TimerServiceImpl(Scheduler scheduler, RabbitTemplate rabbitTemplate) {
        this.scheduler = scheduler;
        this.rabbitTemplate = rabbitTemplate;
    }

    @Override
    public void createTimer(Map<String, Serializable> params) {
        SimpleTimerJob job = SimpleTimerJob.newInstance(params);
        JobDetail jobDetail = job.getJobDetail();
        try {
            scheduler.scheduleJob(jobDetail, job.getTrigger());
            log.info("添加定时任务成功，jobKey=[{}] params=[{}]", jobDetail.getKey(), jobDetail.getJobDataMap().get("params"));
        } catch (SchedulerException e) {
            log.error("添加定时任务失败，jobKey=[{}] params=[{}]", jobDetail.getKey(), jobDetail.getJobDataMap().get("params"));
            e.printStackTrace();
        }
    }

    @Override
    public void triggerTask(String triggerName) {
        Map<String, Serializable> dataMap = new HashMap<>();
        dataMap.put("trigger", triggerName);

        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        rabbitTemplate.convertAndSend(RabbitConfig.EXCHG_SCHEDULE, RabbitConfig.RTKEY_WAIT_EXEC, dataMap, correlationData);
    }

}
